<template>
  <v-chart class="chart"  :option="option" autoresize />
<!--  <div v-else>加载中...</div>-->
<!--  <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>-->
</template>

<script setup>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  ToolboxComponent,
} from 'echarts/components';
import VChart from 'vue-echarts';
import { ref, onMounted } from 'vue';
import { listOrder } from "@/api/shop/order"; // 确保路径正确

use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  LineChart,
  ToolboxComponent,
]);

const option = ref({});
const loading = ref(true);
const errorMessage = ref('');

async function fetchData() {
  loading.value = true;
  errorMessage.value = ''; // 清空之前的错误信息
  try {
    const revenueResponse = await listRevenue({ timestamp: Date.now() });
    console.log('Revenue Response:', revenueResponse); // 打印完整的 API 响应

    // 检查返回的数据结构
    if (!revenueResponse || !revenueResponse.rows) {
      if (revenueResponse && revenueResponse.error) {
        console.error('API 错误:', revenueResponse.error);
        throw new Error('API 返回的错误信息');
      } else {
        throw new Error('API 返回的数据格式不正确');
      }
    }

    // 获取当前日期
    const today = new Date();
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(today.getDate() - 7); // 设置为七天前的日期

    // 从 rows 中提取数据并筛选最近七天的数据
    const filteredRows = revenueResponse.rows.filter(item => {
      const revenueDate = new Date(item.revenueTime); // 假设 revenueTime 是日期字符串
      return revenueDate >= sevenDaysAgo && revenueDate <= today;
    });
    if (filteredRows.length === 0) {
      console.error('没有找到最近七天的数据');
      errorMessage.value = '没有找到最近七天的数据';
      return;
    }
    // 提取筛选后的数据
    const timeData = filteredRows.map(item => item.revenueTime);
    const revenueData = filteredRows.map(item => item.revenueAmount);
    const orderData = filteredRows.map(item => item.orderId); // 假设 orderId 是您想要的订单量
    console.log('Today:', today);
    console.log('Seven Days Ago:', sevenDaysAgo);
    // 根据获取的数据设置图表选项
    option.value = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      toolbox: {
        feature: {
          dataView: {show: true, readOnly: false},
          magicType: {show: true, type: ['line', 'bar']},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      legend: {
        data: ['营业额', '订单量', '预约单量']
      },
      xAxis: [
        {
          type: 'category',
          data: timeData, // 使用提取的时间数据
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '订单量',
          min: 0,
          max: 250,
          interval: 50,
          axisLabel: {
            formatter: '{value} '
          }
        },
        {
          type: 'value',
          name: '营业额',
          min: 0,
          max: 12000,
          interval: 2000,
          axisLabel: {
            formatter: '{value} 元'
          }
        }
      ],
      series: [
        {
          name: '预约单量',
          type: 'bar',
          tooltip: {
            valueFormatter: (value) => value + ' 单'
          },
          data: orderData || [] // 使用正确的 API 返回的数据
        },
        {
          name: '订单量',
          type: 'bar',
          tooltip: {
            valueFormatter: (value) => value + ' 单'
          },
          data: orderData || [] // 使用正确的 API 返回的数据
        },
        {
          name: '营业额',
          type: 'line',
          yAxisIndex: 1,
          tooltip: {
            valueFormatter: (value) => value + ' 元'
          },
          data: revenueData || [] // 使用正确的 API 返回的数据
        }
      ]
    };
  } catch (error) {
    console.error('获取数据失败:', error);
    errorMessage.value = '获取数据失败，请重试'; // 设置错误信息
  } finally {
    loading.value = false;
  }
}

// 在组件挂载时调用 fetchData
onMounted(fetchData);
</script>

<style scoped>
.chart {

  height: 400px; /* 设置为固定高度 */
  width: 100%;   /* 宽度为100%以适应父容器 */
}


</style>
